package com.wontube.core.cron;

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.core.conf.Cron;
import com.wontube.core.utils.ClassUtils;


/**
 * @author yuechao
 *
 */
public final class JobsManager {
	private static final Logger logger = LoggerFactory.getLogger(JobsManager.class);
	private static final HashMap<String, IJobs> map = new HashMap<String, IJobs>();

	public static void loadAllJobs() {
		List<Class<IJobs>> list = ClassUtils.loadSubClasses(IJobs.class);
		map.clear();
		
		logger.info("begin to load all avalible command");
		for (Class<IJobs> clazz : list) {
			try {
				IJobs jobs = clazz.newInstance();
				IJobs oldJobs = map.put(jobs.name(), jobs);
				if (oldJobs != null) {
					logger.warn("duplicated job name {}, please fixed it first!", jobs.name());
				}
			} catch (InstantiationException e) {
				logger.error(e.toString());
			} catch (IllegalAccessException e) {
				logger.error(e.toString());
			}
		}
		
		logger.info("finished loading all avalible command, count = {}", map.size());
	}
	
	public static boolean isCommandSupported(String command) {
		return map.containsKey(command);
	}
	
	public static IJobs getJobs(Cron cron) {
		IJobs jobs = map.get(cron.getCommand());
		return jobs;
	}
	
	/**
	 * @param cron
	 */
	public static void execute(Cron cron) {
		IJobs jobs = map.get(cron.getCommand());
		if (jobs != null) {
			String name = jobs.name();
			String cmdLine = cron.getArgsString();
			String[] args = new String[] {
				name, Boolean.toString(cron.isAsync()), cmdLine
			};
			logger.info("begin to exetute {} jobs, async = {}, args: {}", args);
			jobs.execute(cron.getArguments());
			logger.info("finished exetuting {} jobs, async = {}, args: {}", args);
		}
	}
}
